package com.example.interview.controller;

import com.example.interview.config.R;
import com.example.interview.domain.Commodity;
import com.example.interview.domain.Order;
import com.example.interview.service.CommodityService;
import com.example.interview.service.OrderService;
import com.example.interview.service.UserService;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    OrderService service;

    @Resource
    UserService userService;

    @Resource
    CommodityService commodityService;

    /**
     * 消费商品的接口
     * @param userId 用户id信息
     * @param goodsId 商品id信息
     * @param quantity 购买数量
     * @return  返回消费信息
     */
    @PostMapping("/addOrder")
    public R addOrder(long userId,long goodsId,double quantity) {
        Commodity commodity = commodityService.queryCommodityById(goodsId);
        BigDecimal total = commodity.getPrice().multiply(BigDecimal.valueOf(quantity)) ;
        BigDecimal balance = userService.queryBalance(userId);

        if (balance.compareTo(total) >= 0) {
            service.addOrder(userId, goodsId, BigDecimal.valueOf(quantity));
            // 余额减去消费金额
            userService.setMoney(userId, total.multiply(BigDecimal.valueOf(-1)));
            // 消费成功
            return R.success("success");
        } else {
            // 余额不足
            return R.fail("fail");
        }
    }

    /**
     * 退货的接口
     * @param orderId 订单id信息
     * @return  返回成功退货信息
     */
    @PostMapping("/refund")
    public R refund(long orderId) {
        Order order = service.queryOrderByOrderId(orderId);
        Commodity commodity = commodityService.queryCommodityById(order.getGoodsId());
        BigDecimal total = commodity.getPrice().multiply(order.getQuantity()) ;
        // 用户余额消费金额退回
        userService.setMoney(order.getUserId(), total);
        //订单状态修改
        service.updateOrderStatusById(orderId);
        return R.success("success");
    }

    /**
     * 查询用户消费信息
     * @param userId 用户id
     * @return  返回所有订单信息
     */
    @PostMapping("/refund")
    public R detailed(long userId) {
        List<Order> list = service.queryOrderByUserId(userId);
        R<Object> success = R.success("success");
        success.setData(list);
        return success;
    }

}
